S.tab = {}
$head = $('.tab-head')
$body = $('.tab-body')

id = 0
tabNum = 0
activeId = -1

byKey = {}
byId = {}
history = []

showTab = (object)->
    activeId = object.id
    _.remove history, (n)-> n == activeId
    history.push activeId
    $head.find('.tab').removeClass('active')
    object.$tab.addClass('active')

    $body.find('.view').hide()
    object.$view.show()

closeTab = (object)->
    console.log 'close id' + object.id
    tabNum--
    object.$tab.remove()
    object.$view.remove()

    byId[object.id] = false
    byKey[object.key] = false if object.key?

    _.remove history, (n)-> n == object.id
    if object.id == activeId and history.length # 关闭了活跃的标签页
        id = history[history.length - 1]
        console.log 'close active, so show' + id
        showTab byId[id]

S.tab.exists = (key)->
    byKey[key]

S.tab.showByKey = (key)->
    showTab byKey[key]

S.tab.closeById = (id)->
    closeTab byId[id]

S.tab.replaceTab = (title, $view, key)->
    if key and byKey[key]
        object = byKey[key]
        closeTab(object)
        byKey[key] = false
    S.tab.openTab(title, $view, key)

S.tab.openTab = (title, $view, key)->
    if key and byKey[key]
        showTab byKey[key]
        return byKey[key].id
    else
        id++
        tabNum++

        object = {}
        object.id = id
        object.key = key
        byId[id] = object
        byKey[key] = object if key?

        $tab = $(ST.Tab(title: title)).appendTo($head)
        object.$tab = $tab
        # 设置大小
        headWidth = $head[0].clientWidth
        tabWidth = Math.min(headWidth / 8, (headWidth - 30) / tabNum)
        $head.find('.tab').width(tabWidth - 3)

        object.$view = $view
        $body.append $view

        showTab object

        $tab.find('.title').click ->
            showTab object

        $tab.find('.close').click ->
            closeTab object

        return id
